using System;

namespace Voodoo.Sauce.Internal.Ads
{
	public class InterstitialAd
	{
		private const string TAG = "InterstitialAd";

		public Action OnComplete;

		public Action OnAdClicked;

		public Action OnAdLoaded;

		public Action OnAdFailed;

		protected string _adUnit;

		private string _mediation;

		private bool _loaded;

		private bool _autofetch;

		private ExponentialBackoff.ExpBackoff _backoff;

		public InterstitialAd(string mediation, string adUnit, bool autofetch)
		{
			DebugLog("Creating an interstitial for ad unit " + adUnit);
			_mediation = mediation;
			_adUnit = adUnit;
			_autofetch = autofetch;
			_backoff = ExponentialBackoff.CreateExpBackoff(Fetch, "InterstitialAd");
		}

		protected virtual void Fetch()
		{
			DebugLog("Fetch");
			_loaded = false;
		}

		protected void AutoFetch()
		{
			if (_autofetch)
			{
				_backoff.Start();
			}
			else
			{
				DebugLog("AUTOFETCH IS DISABLED. IF THIS IS FOR TEST PURPOSES, IGNORE THIS MESSAGE");
			}
		}

		public virtual void Show()
		{
			DebugLog("Show");
		}

		public virtual bool IsLoaded()
		{
			return _loaded;
		}

		protected void Complete()
		{
			_loaded = false;
			if (OnComplete != null)
			{
				OnComplete();
			}
			OnComplete = null;
			AutoFetch();
		}

		public void Destroy()
		{
			DebugLog("Destroy");
			UnregisterEvents();
		}

		protected virtual void RegisterEvents()
		{
			DebugLog("RegisterEvents");
		}

		protected virtual void UnregisterEvents()
		{
			DebugLog("UnregisterEvents");
			OnComplete = null;
			OnAdClicked = null;
			OnAdFailed = null;
			OnAdLoaded = null;
		}

		protected void OnAdLoadedCallback()
		{
			DebugLog("OnAdLoadedCallback");
			_backoff.Reset();
			_loaded = true;
			if (OnAdLoaded != null)
			{
				OnAdLoaded();
			}
		}

		protected void OnAdClickedCallback()
		{
			DebugLog("OnAdClickedCallback");
			if (OnAdClicked != null)
			{
				OnAdClicked();
			}
		}

		protected void OnAdClosedCallback()
		{
			DebugLog("OnAdClosedCallback");
			Complete();
		}

		protected void OnAdExpiredCallback()
		{
			DebugLog("OnAdExpiredCallback");
			AutoFetch();
		}

		protected void OnAdFailedCallback()
		{
			DebugLog("OnAdFailedCallback");
			AutoFetch();
			if (OnAdFailed != null)
			{
				OnAdFailed();
			}
		}

		protected void DebugLog(string message)
		{
			VoodooLog.Log("InterstitialAd", $"InterstitialAd - Mediation: {_mediation} - AdUnit: {_adUnit} - {message}");
		}
	}
}
